package com.hfjava.ebook.controller;

import com.hfjava.ebook.common.JsonResult;
import com.hfjava.ebook.entity.Book;
import com.hfjava.ebook.entity.BookPageDto;
import com.hfjava.ebook.entity.Pageable;
import com.hfjava.ebook.server.BookService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.awt.*;

@RestController
@RequestMapping("/book")
public class BookController {
    @Resource
    private BookService bookService;

    // 从前端传JSON字符串 {"cid":2,"page":1,"limit":3,"sortField":"hits","sortDir":1} 到后台,请求参数自动发生映射


    @RequestMapping(value = "/search",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public JsonResult listPage(@RequestBody BookPageDto bookPageDto){
        Pageable pageable = bookService.findByPage(bookPageDto.getCid(),bookPageDto.getPage(),bookPageDto.getLimit(),
                bookPageDto.getSortField(),bookPageDto.getSortDir());
        return JsonResult.ok(pageable);
    }
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public JsonResult bookAdd(@RequestBody Book book){
        int retVal = bookService.saveBook(book);
        if (retVal > 0) {
            return JsonResult.success("新增电子图书信息成功!");
        }else {
            return JsonResult.success("新增电子图书信息失败!");
        }
    }

    @RequestMapping(value = "/detail/{bid}" , method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
        public JsonResult bookDetail(@PathVariable int bid){
        Book book = bookService.findBookById(bid);
        return JsonResult.ok(book);
    }

    @RequestMapping(value = "/update" , method = RequestMethod.POST)
    public JsonResult bookUpdate(@RequestBody Book book){
        int retVal = bookService.modifyBook(book);
        if (retVal > 0) {
            return JsonResult.success("修改电子图书信息成功!");
        }else {
            return JsonResult.success("修改电子图书信息失败!");
        }
    }
    @RequestMapping(value = "/delete/{bid}" , method = RequestMethod.GET)
    public JsonResult bookUpdate(@PathVariable Integer bid){
        int retVal = bookService.deleteBookById(bid);
        if (retVal > 0) {
            return JsonResult.success("删除电子图书信息成功!");
        }else {
            return JsonResult.success("删除电子图书信息失败!");
        }
    }
}
